package com.taobao.auto;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.taobao.tql.scan.ScanGet;

/**
 * 自动生成testng测试类
 * 
 * @author jill
 * 
 */
public class GenTestClassTool {
	private String className = "TQLQuery";

	private String[] methodnames; // 方法名称数组

	private Type[] rtnTypes; // 方法返回类型数组

	private int[] colSizes; // 列名大小数组

	private boolean f_testng = false; // 是否需要导入包java.util.*

	private boolean f_junit = false; // 是否需要导入包java.sql.*
	public static final String CLASS_COMM_NAME = "newClassTest";

	private static Map<String, Class> tempMap = null;

	/**
	 * 
	 * @return
	 */
	public Map<String, Class> geBusiApi() {
		if (tempMap == null) {
			tempMap = new HashMap<String, Class>();
		}
		ScanGet scanGet = new ScanGet();
		Set<Class<?>> apiClasses = scanGet
				.getClasses("com.taobao.api.request.");
		for (Class tempCls : apiClasses) {
			String className = tempCls.getName();
			// 过滤DO
			// 过滤接口
			int flag = tempCls.getModifiers();
			if (Modifier.isInterface(flag)) {
				continue;
			}
			// 过滤DAO
			//过滤test
			

			System.out.println(className + ":::::" + tempCls.getName());
			tempMap.put(className.toLowerCase(), tempCls);
		}
		return tempMap;
	}

	public GenTestClassTool() {
		ScanGet scanGet = new ScanGet();
		Set<Class<?>> apiClasses = scanGet
				.getClasses("com.taobao.tql");
		for (Class tempCls : apiClasses) {
			int size = apiClasses.size(); // 共有多少class
			// 过滤DO
			// 过滤接口
			int flag = tempCls.getModifiers();
			if (Modifier.isInterface(flag)) {
				continue;
			}
			// 过滤DAO
			//过滤test
			if(tempCls.getName().indexOf("test") >= 0 || tempCls.getName().indexOf("Test") >= 0) {
				continue;
			}
			Method[] methods = tempCls.getMethods();// 获得类的所有公共方法
			if (methods != null) {
				StringBuilder methBuild = new StringBuilder();
				if (f_testng) {
					methBuild.append("import java.util.Date;\r\n");
				}
				if (f_junit) {
					methBuild.append("import java.sql.*;\r\n\r\n\r\n");
				}
				methBuild.append("public class "
						+ initcap(tempCls.getName() + "Test") + " {\r\n");

				methBuild.append("" + tempCls.getName() + " " + CLASS_COMM_NAME
						+ " = new " + tempCls.getName() + "()\r\n");

				methodnames = new String[methods.length];// 每个类多少个方法
				rtnTypes = new Type[methods.length];
				colSizes = new int[size];
				int i = 0;
				// 非私有方法
				//if (rtnTypes[i].getClass().isPrimitive()) {
					f_testng = true;
				//}
				//if (rtnTypes[i].getClass().isPrimitive()) {
					f_junit = true;
				//}

				for (Method tempMethod : methods) {
					methodnames[i] = tempMethod.getName();
					
					Class[] methodClass = tempMethod.getParameterTypes();
					if(tempMethod.getReturnType() != null) {
						rtnTypes[i] = tempMethod.getReturnType();
						// colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
						methBuild.append(parse(methodnames[i], rtnTypes[i],
								methodClass));
						i++;
					}
				}
				methBuild.append("}\r\n");
				try {
					// 生成test文件
					FileWriter fw = new FileWriter("c:\\" + tempCls.getName() + "Test"
							+ ".java");
					PrintWriter pw = new PrintWriter(fw);
					pw.println(methBuild.toString());
					pw.flush();
					pw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 解析处理(生成实体类主体代码)
	 */
	private String parse(String methodName, Type rtnTypes, Class[] paramClass) {
		StringBuilder sb = new StringBuilder();
		sb.append("\tpublic void test" + methodName + "(){\r\n");
		for (Class tempClass : paramClass) {
			if (tempClass.getName().equals("String")) {
				sb.append("String tempStr = \"liqfTest\";");
			}
			sb.append(CLASS_COMM_NAME).append(".").append(methodName);
			sb.append("(").append("tempStr").append(")");
			
		}
		sb.append("\t}\r\n");

		System.out.println(sb.toString());
		return sb.toString();

	}

	/**
	 * 生成所有的方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb) {
		for (int i = 0; i < methodnames.length; i++) {
			sb.append("\tpublic void test" + initcap(methodnames[i])
					+ "(){\r\n");
			sb.append("\t\tthis." + methodnames[i] + "=" + methodnames[i]
					+ ";\r\n");
			sb.append("\t}\r\n");

			// sb.append("\tpublic " + sqlType2JavaType(rtnTypes[i]) + " get"
			// + initcap(methodnames[i]) + "(){\r\n");
			// sb.append("\t\treturn " + methodnames[i] + ";\r\n");
			sb.append("\t}\r\n");
		}
	}

	/**
	 * 解析输出属性
	 * 
	 * @return
	 */
	private void processAllAttrs(StringBuffer sb) {
		for (int i = 0; i < methodnames.length; i++) {
			// sb.append("\tprivate " + sqlType2JavaType(rtnTypes[i]) + " "
			// + methodnames[i] + ";\r\n");

		}
	}

	/**
	 * 把输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	private String initcap(String str) {
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return new String(ch);
	}

	private String sqlType2JavaType(String sqlType) {
		if (sqlType.equalsIgnoreCase("bit")) {
			return "bool";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "byte";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "short";
		} else if (sqlType.equalsIgnoreCase("int")) {
			return "int";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return "long";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "float";
		} else if (sqlType.equalsIgnoreCase("decimal")
				|| sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real")) {
			return "double";
		} else if (sqlType.equalsIgnoreCase("money")
				|| sqlType.equalsIgnoreCase("smallmoney")) {
			return "double";
		} else if (sqlType.equalsIgnoreCase("varchar")
				|| sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar")
				|| sqlType.equalsIgnoreCase("nchar")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("datetime")) {
			return "Date";
		}

		else if (sqlType.equalsIgnoreCase("image")) {
			return "Blob";
		} else if (sqlType.equalsIgnoreCase("text")) {
			return "Clob";
		}
		return null;
	}

	public static void main(String[] args) {
		new GenTestClassTool();
	}
}
